import sys
from socket import *
from threading import Thread
from config import *
import re
import json

# 服务器地址
ADDR = (HOST, PORT)


# 创建和web_frame交互的套接字
def connect_web_frame(env):
    new_socket = socket()
    try:
        new_socket.connect((frame_ip, frame_port))
    except Exception as e:
        print(e)
        return
    result = json.dumps(env)
    new_socket.send(result.encode())
    web_frame_recv = new_socket.recv(102400).decode()
    return web_frame_recv

class HTTPServer:
    def __init__(self):
        self.address = ADDR
        self.create_socket()
        self.bind()

    # 创建套接字
    def create_socket(self):
        self.server = socket()
        self.server.setsockopt(SOL_SOCKET, SO_REUSEADDR, DEBUG)



    # 绑定地址
    def bind(self):
        self.server.bind(self.address)
        self.ip = self.address[0]
        self.port = self.address[1]

    # 启动服务
    def sever_forever(self):
        self.server.listen(5)
        print("listening on %s:" % self.port)
        while True:
            conn, addr = self.server.accept()
            print("connect from",addr)
            client = Thread(target=self.do_request, args=(conn,))
            client.daemon = True
            client.start()

    # 处理客户端请求
    def do_request(self, conn):
        data = conn.recv(4096).decode('utf-8')
        pattern=r"(?P<method>[A-Z]+)\s+(?P<path>/\S*)"
        try:
            env=re.match(pattern,data).groupdict()
        except Exception as e:
            print(e)
            conn.close()
        else:
            web_frame_recv=connect_web_frame(env)
            if not web_frame_recv:
                return
            self.response(web_frame_recv,conn)


    def response(self, web_frame_recv,conn):
        data=json.loads(web_frame_recv)
        if data['status']==200:
            result="HTTP/1.1 200 OK\r\n"
            result+="Content-Type: text/html\r\n"
            result+="\r\n"
            result+=data["data"]
            conn.send(result.encode())

        elif data['status']==404:
            result="HTTP/1.1 404 NOT FOUND\r\n"
            result+="Content-Type: text/html\r\n"
            result+="\r\n"
            result+=data["data"]
            conn.send(result.encode())

        elif data['status']==500:
            pass








if __name__ == "__main__":
    http = HTTPServer()
    http.sever_forever()
